<script setup lang="ts">
import AddDraw from "./components/add-draw.vue"
import { onMounted, ref } from "vue"
import { CommentApi, OrganizationApi, ContactApi } from "@/api/crm"
import router from "@/router"
import type { contactData, organizationData } from "./types/comment"
import type { CommentData } from "@/api/crm/types/comment"
defineOptions({
  name: "Comment"
})
const commentData = ref<CommentData[]>()
const commentListInfo = ref({
  pageSize: 0,
  currentPage: 1,
  total: 0
})

/**对子组件的控制和传值 */
const drawRef = ref()
const addComment = () => {
  drawRef.value.show = true
  getContact()
  getOrganization()
}
/**提交表单的空表数据 */
const commentDefaultForm = {
  subject: "",
  org_id: "",
  contact_id: "",
  //   orgId: "",
  //   fullname: ""
  // },
  // contact: {
  //   contactId: "",
  //   name: ""
  // },
  date: "",
  content: ""
}

const commentForm = ref(commentDefaultForm)

const contactList = ref<contactData[]>()
const orgList = ref<organizationData[]>()

/**添加沟通数据 */
const submit = () => {
  CommentApi.addComment(commentForm.value)
  commentForm.value = commentDefaultForm
  getDisplayData()
}

/**获取展示表格数据 */
const getDisplayData = async (page: number = 1, subject: string = "") => {
  let resp = await CommentApi.getCommentList({ page, subject })
  commentData.value = resp.data.result
  let { total, pageSize, currentPage } = resp.data
  commentListInfo.value = {
    total,
    pageSize,
    currentPage
  }
}

/**页码改变 */
const handlePageChange = (page: number) => {
  getDisplayData(page)
}
/**动态索引部分，key值 */
const enum actionKey {
  contact = "contact",
  organization = "organization"
}
interface OpInterface {
  promptMsg: string
  promptTitle: string
  // api: object
  // key: string
  successAction: any // 有点疑惑，用object就会报错
}
/**key值格式 */
type ActionType = Record<actionKey, OpInterface>
/**快速添加联系人成功回调 */
const contactAction = async (value: string) => {
  let resp = await ContactApi.addContact({ name: value })
  getContact()
  commentForm.value.contact_id = resp.data.id
  // commentForm.value.name = value
  ElMessage({
    type: "success",
    message: `联系人【${value}】已添加！`
  })
}
/**快速添加组织机构成功回调 */
const organizationAction = async (value: string) => {
  let resp = await OrganizationApi.addOrganization({ fullname: value })
  getOrganization()
  commentForm.value.org_id = resp.data.id
  // commentForm.value.organization.fullname = value
  ElMessage({
    type: "success",
    message: `机构【${value}】已添加！`
  })
}

const action: ActionType = {
  contact: {
    promptMsg: "请输入联系人名称（后续请至联系人板块完善信息）：",
    promptTitle: "快速添加联系人",
    successAction: contactAction
  },
  organization: {
    promptMsg: "请输入机构名称（后续请至机构板块完善信息）：",
    promptTitle: "快速添加机构",
    successAction: organizationAction
  }
}

/**快捷新增联系人 */
const quickAdd = (e: keyof typeof actionKey) => {
  // console.log(e)
  // ElMessageBox.prompt("请输入联系人名称（后续请至联系人板块完善信息）：", "快速添加联系人", {
  ElMessageBox.prompt(action[e].promptMsg, action[e].promptTitle, {
    confirmButtonText: "确定",
    cancelButtonText: "取消"
    // inputPattern:
    //   /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
    // inputErrorMessage: 'Invalid Email',
  })
    .then(async ({ value }) => {
      action[e].successAction(value)
      // let resp = await ContactApi.addContact({ action[e].key: value })
      // // 重新获取联系人名单
      // getContact()
      // commentForm.value.contact.contactId = resp.data.id
      // commentForm.value.contact.name = value
      // ElMessage({
      //   type: "success",
      //   // message: `联系人【${value}】已添加！`
      //   message: `联系人【${value}】已添加！`
      // })
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消添加"
      })
    })
}

/** 获取联系人列表 */
async function getContact() {
  let resp = await ContactApi.getAllContactList()
  let cList = resp.data
  // 处理联系人数据，只保留_id(改为contactId) 和name
  contactList.value = cList.map(({ name, id }) => {
    return { name, id }
  })
}

/** 获取机构列表 */
async function getOrganization() {
  let resp = await OrganizationApi.getOrganizationList()
  console.log("机构", resp.data)
  let oList = resp.data
  // 处理联系人数据，只保留_id(改为contactId) 和name
  orgList.value = oList.map(({ fullname, id }) => {
    return { fullname, id }
  })
}

/**打开时获取列表展示数据 */
onMounted(async () => {
  getDisplayData()
  // console.log(await filterCommentApi({page:1,subject:''}));
})
/**关闭drawer前hook，一般为清空 */
function beforeCloseHook() {
  commentForm.value = commentDefaultForm
}
/**前往详情页 */
const goDetail = (id: string) => {
  // const goDetail = (e) => {
  // console.log(id)
  router.push({ path: "/crm/comment/detail", query: { id } })
}
</script>

<template>
  <div class="layout-container">
    <!-- 第一个卡片 -->
    <el-card>
      <!-- 搜索功能 -->
      <el-button type="primary" @click="addComment">添加</el-button>
    </el-card>
    <!-- 第二个卡片 -->
    <el-card style="margin-top: 15px">
      <el-table :data="commentData">
        <el-table-column type="index" label="序号" width="80"></el-table-column>
        <el-table-column label="沟通主题">
          <template #default="scope">
            <el-link type="primary" @click="goDetail(scope.row.id)">{{ scope.row.subject }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="contact.name" label="联系人"></el-table-column>
        <el-table-column prop="organization.fullname" label="相关机构"></el-table-column>
        <!-- <el-table-column label="操作">
          <template #default="scope">
            <el-button type="default" @click="handle"></el-button>
          </template>
        </el-table-column> -->
      </el-table>
      <!-- 翻页功能 -->
      <el-pagination
        :total="commentListInfo.total"
        :current-page="commentListInfo.currentPage"
        :page-size="commentListInfo.pageSize"
        @current-change="handlePageChange"
        layout="prev, pager, next,->,total"
      ></el-pagination>
    </el-card>
    <!-- 添加/编辑信息的drawer -->
    <AddDraw ref="drawRef" :submit="submit" :beforeCloseHook="beforeCloseHook">
      <template #header> 添加沟通记录 </template>
      <template #body>
        <el-form :model="commentForm" label-width="20%">
          <el-form-item label="沟通主题">
            <el-input v-model="commentForm.subject" placeholder="输入沟通主题"></el-input>
          </el-form-item>
          <el-form-item label="联系人">
            <el-select v-model="commentForm.contact_id" placeholder="请选择联系人" filterable>
              <el-option v-for="c in contactList" :key="c.id" :label="c.name" :value="c.id"></el-option>
              <template #empty>
                <el-link type="primary" @click="quickAdd('contact')">联系人不存在，点击添加</el-link>
              </template>
            </el-select>
          </el-form-item>
          <el-form-item label="沟通日期">
            <el-date-picker
              v-model="commentForm.date"
              type="date"
              placeholder="选择沟通日期"
              size="default"
              value-format="YYYY-MM-DD"
            />
            <!-- <el-input v-model="commentForm.date" placeholder="输入联系人"> </el-input> -->
          </el-form-item>
          <el-form-item label="相关机构">
            <el-select v-model="commentForm.org_id" value-key="orgId" placeholder="请选择相关机构" filterable>
              <el-option v-for="o in orgList" :key="o.id" :label="o.fullname" :value="o.id"></el-option>
              <template #empty>
                <el-link type="primary" @click="quickAdd('organization')">相关机构不存在，点击添加</el-link>
              </template>
            </el-select>
          </el-form-item>
          <el-form-item label="沟通内容">
            <el-input
              v-model="commentForm.content"
              placeholder="输入沟通内容：可以是具体内容，推测等"
              type="textarea"
              :rows="6"
            ></el-input>
          </el-form-item>
        </el-form>
      </template>
    </AddDraw>
  </div>
</template>

<style lang="scss" scoped>
.el-pagination {
  margin: 20px auto 0px;
  width: 300px;
  display: flex;
  justify-content: right;
}
</style>
